﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using University.Workshop.Model;
using University.Workshop.DataAccess;
using University.Workshop.Business;

namespace University.Workshop.WebApp
{
	public partial class BuyWithGiftCard : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            Product productBought = ProductDataAccess.GetProductById(long.Parse(Request["ProductId"]));
            float quantitySpended = float.Parse(Request["QuantitySpended"]);
            short itemsQuantity = short.Parse(Request["itemsQuantity"]); //how many items of the product were bought

            User user = UserDataAccess.GetUserByEmail(User.Identity.Name);
            GiftCard mygiftcard = GiftCardManager.GetGiftCardByRecipientId(user.Id);
            mygiftcard.Quantity = mygiftcard.Quantity - quantitySpended;
            if (quantitySpended == mygiftcard.Quantity)
                mygiftcard.Available = "No";
            GiftCardDataAccess.ModifyQuantity(mygiftcard.GiftCardId, mygiftcard.Quantity);
            GiftCard newgiftcard = GiftCardManager.GetGiftCardByRecipientId(user.Id);
            productBought = UpdateProductInformation(productBought, itemsQuantity);
            LoadLabels(newgiftcard, productBought);
		}
        protected void LoadLabels(GiftCard gf, Product prod)
        {
            this.prodNameLabel.Text = prod.Name;
            this.prodPriceLabel.Text = prod.Price.ToString();
            this.prodCurrencyLabel.Text = prod.Currency;
            this.QuantityLabel.Text = gf.Quantity.ToString();
            this.CurrencyLabel.Text = gf.Currency;
        }
        protected Product UpdateProductInformation(Product product, short itemsQuantity)
        {
            if (product.Quantity == itemsQuantity)
            {
                product.Status = "Sold";
                product.Quantity = 0;
            }
            else
                product.Quantity = short.Parse((int.Parse(product.Quantity.ToString()) - int.Parse(itemsQuantity.ToString())).ToString());
            return ProductDataAccess.ModifyProduct(product);
        }
	}
}